import fs from 'fs-extra';
import path from 'path';
import { Agent, CreateAgentInput, UpdateAgentInput, FileOperationResult, PaginationQuery, PaginatedResponse, AgentStats } from '../types/agent';
import { PATHS } from '../config';

/**
 * 文件服务类 - 负责智能体数据的文件操作
 */
export class FileService {
  private agentsFilePath: string;
  private backupPath: string;

  constructor() {
    this.agentsFilePath = path.join(PATHS.DATA, 'agents.json');
    this.backupPath = PATHS.BACKUP;
    this.initializeDataDirectory();
  }

  /**
   * 初始化服务
   */
  async initialize(): Promise<void> {
    await this.initializeDataDirectory();
  }

  /**
   * 初始化数据目录
   */
  private async initializeDataDirectory(): Promise<void> {
    try {
      // 确保数据目录存在
      await fs.ensureDir(PATHS.DATA);
      await fs.ensureDir(this.backupPath);
      
      // 如果agents.json不存在，创建空文件
      if (!(await fs.pathExists(this.agentsFilePath))) {
        await fs.writeJson(this.agentsFilePath, [], { spaces: 2 });
        console.log('Created initial agents.json file');
      }
    } catch (error) {
      console.error('Failed to initialize data directory:', error);
      throw error;
    }
  }

  /**
   * 读取所有智能体数据
   */
  async getAllAgents(): Promise<Agent[]> {
    try {
      const agents = await fs.readJson(this.agentsFilePath);
      return Array.isArray(agents) ? agents : [];
    } catch (error) {
      console.error('Failed to read agents file:', error);
      return [];
    }
  }

  /**
   * 根据ID获取智能体
   */
  async getAgentById(id: string): Promise<Agent | null> {
    try {
      const agents = await this.getAllAgents();
      return agents.find(agent => agent.id === id) || null;
    } catch (error) {
      console.error('Failed to get agent by ID:', error);
      return null;
    }
  }

  /**
   * 分页查询智能体
   */
  async getAgentsPaginated(query: PaginationQuery): Promise<PaginatedResponse<Agent>> {
    try {
      let agents = await this.getAllAgents();
      
      // 应用过滤条件
      if (query.category) {
        agents = agents.filter(agent => agent.category === query.category);
      }
      
      if (query.search) {
        const searchLower = query.search.toLowerCase();
        agents = agents.filter(agent => 
          agent.name.toLowerCase().includes(searchLower) ||
          (agent.description || '').toLowerCase().includes(searchLower) ||
          agent.author.toLowerCase().includes(searchLower)
        );
      }
      
      if (query.tags && query.tags.length > 0) {
        agents = agents.filter(agent => 
          query.tags!.some(tag => agent.tags.includes(tag))
        );
      }
      
      // 排序（按创建时间倒序）
      agents.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
      
      // 分页
      const page = query.page || 1;
      const limit = query.limit || 10;
      const startIndex = (page - 1) * limit;
      const endIndex = startIndex + limit;
      
      const paginatedAgents = agents.slice(startIndex, endIndex);
      
      return {
        items: paginatedAgents,
        total: agents.length,
        page,
        limit,
        totalPages: Math.ceil(agents.length / limit)
      };
    } catch (error) {
      console.error('Failed to get paginated agents:', error);
      throw error;
    }
  }

  /**
   * 创建新智能体
   */
  async createAgent(input: CreateAgentInput): Promise<FileOperationResult> {
    try {
      const agents = await this.getAllAgents();
      
      // 生成唯一ID
      const id = this.generateId();
      const now = new Date().toISOString();
      
      const newAgent: Agent = {
        id,
        ...input,
        description: input.description || '',
        usage: input.usage || '',
        config: input.config || {},
        createdAt: now,
        updatedAt: now
      };
      
      agents.push(newAgent);
      
      // 创建备份
      await this.createBackup();
      
      // 保存到文件
      await fs.writeFile(this.agentsFilePath, JSON.stringify(agents, null, 2), 'utf8');
      
      return {
        success: true,
        message: 'Agent created successfully',
        data: newAgent
      };
    } catch (error) {
      console.error('Failed to create agent:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 更新智能体
   */
  async updateAgent(id: string, input: UpdateAgentInput): Promise<FileOperationResult> {
    try {
      const agents = await this.getAllAgents();
      const agentIndex = agents.findIndex(agent => agent.id === id);
      
      if (agentIndex === -1) {
        return {
          success: false,
          error: 'Agent not found'
        };
      }
      
      // 创建备份
      await this.createBackup();
      
      // 更新智能体
      agents[agentIndex] = {
        ...agents[agentIndex],
        ...input,
        updatedAt: new Date().toISOString()
      };
      
      // 保存到文件
      await fs.writeFile(this.agentsFilePath, JSON.stringify(agents, null, 2), 'utf8');
      
      return {
        success: true,
        message: 'Agent updated successfully',
        data: agents[agentIndex]
      };
    } catch (error) {
      console.error('Failed to update agent:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 删除智能体
   */
  async deleteAgent(id: string): Promise<FileOperationResult> {
    try {
      const agents = await this.getAllAgents();
      const agentIndex = agents.findIndex(agent => agent.id === id);
      
      if (agentIndex === -1) {
        return {
          success: false,
          error: 'Agent not found'
        };
      }
      
      // 创建备份
      await this.createBackup();
      
      // 删除智能体
      const deletedAgent = agents.splice(agentIndex, 1)[0];
      
      // 保存到文件
      await fs.writeFile(this.agentsFilePath, JSON.stringify(agents, null, 2), 'utf8');
      
      return {
        success: true,
        message: 'Agent deleted successfully',
        data: deletedAgent
      };
    } catch (error) {
      console.error('Failed to delete agent:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 获取智能体统计信息
   */
  async getAgentStats(): Promise<AgentStats> {
    try {
      const agents = await this.getAllAgents();
      
      const categories: Record<string, number> = {};
      const tags: Record<string, number> = {};
      
      // 统计分类和标签
      agents.forEach(agent => {
        // 统计分类
        categories[agent.category] = (categories[agent.category] || 0) + 1;
        
        // 统计标签
        agent.tags.forEach(tag => {
          tags[tag] = (tags[tag] || 0) + 1;
        });
      });
      
      // 统计最近添加的智能体（7天内）
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      const recentlyAdded = agents.filter(agent => 
        new Date(agent.createdAt) > sevenDaysAgo
      ).length;
      
      return {
        total: agents.length,
        categories,
        tags,
        recentlyAdded
      };
    } catch (error) {
      console.error('Failed to get agent stats:', error);
      throw error;
    }
  }

  /**
   * 获取统计信息（别名方法）
   */
  async getStats(): Promise<{ total: number; categories: Record<string, number>; tags: Record<string, number> }> {
    return this.getAgentStats();
  }

  /**
   * 创建数据备份
   */
  private async createBackup(): Promise<void> {
    try {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const backupFileName = `agents-backup-${timestamp}.json`;
      const backupFilePath = path.join(this.backupPath, backupFileName);
      
      if (await fs.pathExists(this.agentsFilePath)) {
        await fs.copy(this.agentsFilePath, backupFilePath);
        
        // 清理旧备份（保留最近10个）
        await this.cleanupOldBackups();
      }
    } catch (error) {
      console.error('Failed to create backup:', error);
    }
  }

  /**
   * 清理旧备份文件
   */
  private async cleanupOldBackups(): Promise<void> {
    try {
      const backupFiles = await fs.readdir(this.backupPath);
      const agentBackups = backupFiles
        .filter((file: string) => file.startsWith('agents-backup-') && file.endsWith('.json'))
        .sort()
        .reverse(); // 最新的在前
      
      // 保留最近10个备份
      const filesToDelete = agentBackups.slice(10);
      
      for (const file of filesToDelete) {
        await fs.remove(path.join(this.backupPath, file));
      }
    } catch (error) {
      console.error('Failed to cleanup old backups:', error);
    }
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return `agent_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 导出数据
   */
  async exportData(): Promise<Agent[]> {
    return await this.getAllAgents();
  }

  /**
   * 导入数据
   */
  async importData(agents: Agent[]): Promise<FileOperationResult> {
    try {
      // 验证数据格式
      if (!Array.isArray(agents)) {
        return {
          success: false,
          error: 'Invalid data format: expected array'
        };
      }
      
      // 创建备份
      await this.createBackup();
      
      // 保存导入的数据
      await fs.writeJson(this.agentsFilePath, agents, { spaces: 2 });
      
      return {
        success: true,
        message: `Successfully imported ${agents.length} agents`,
        data: { count: agents.length }
      };
    } catch (error) {
      console.error('Failed to import data:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }
}

// 导出单例实例
export const fileService = new FileService();